<template>
  <div>
    <el-dialog :title="title" :visible.sync="show" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="单元" prop="unitList">
          <i
            class="el-icon-circle-plus"
            style="
              color: #66b1ff;
              font-size: 24px;
              cursor: pointer;
              margin-left: 8px;
            "
            @click="addUnit"
          ></i>
        </el-form-item>
        <el-row
          v-for="(item, index) in form.unitList"
          :key="index"
          :gutter="10"
          style="margin: 10px 0"
        >
          <el-col :span="11">
            <el-form-item
              label="单元名称"
              :prop="'unitList.' + index + '.unitName'"
              :rules="[
                {
                  required: true,
                  message: '请输入单元名称',
                  trigger: 'blur',
                },
              ]"
            >
              <el-input
                v-model="item.unitName"
                placeholder="请输入单元名称"
                style="width: 240px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item
              label="层数"
              :prop="'unitList.' + index + '.floors'"
              :rules="[
                {
                  required: true,
                  message: '请输入楼层',
                  trigger: 'blur',
                },
              ]"
            >
              <el-input
                v-model.number="item.floors"
                type="number"
                placeholder="请输入楼层"
                style="width: 240px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="2" style="display: flex; align-items: center">
            <i
              class="el-icon-remove-outline"
              style="
                color: #e63f32;
                font-size: 24px;
                margin-left: 20px;
                margin-top: 6px;
                cursor: pointer;
              "
              @click="delUnit(index, item)"
            ></i>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { debounce } from '@/utils'
import { addBuilding, addEstate, batchAddUnit, delUnit, editBuilding, editEstate } from '@/api/house/estate'

export default {
  name: 'add',
  components: {  },
  dicts: [],
  props: {
    title: {
      type: String,
      default: '新增单元'
    },
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => {
      }
    },
    designatedData: {
      type: Object,
      default: () => {
      }
    }
  },
  data() {
    return {
      region: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        unitList: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (
                value.some((e) => {
                  return e.unitName === ''
                }) || value.length === 0
              ) {
                callback(new Error('请填写单元'))
              } else {
                callback()
              }
            }
          }
        ]
      }
    }
  },
  computed: {
    show: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    show(val) {
      if (val) {
        this.init()
      }
    },
  },
  methods: {
    init() {
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        // region: [],
        // estateName: '', //楼盘名称
        // provinceId: '', //省
        // cityId: '', //市
        // districtId: '', //区
        // streetId: '', //所属街道
        // communityId: '', //所属社区
        // premisesAddress: '', //小区地址
        // buildingName: '', //楼栋名称
        unitList: [
          {
            unitName: '',
            floors: null,
            buildingId: this.designatedData.buildingId,
          }
        ]
      }
      this.resetForm('form')
    },
    cancel() {
      this.reset()
      this.show = false
    },
    //删除单元
    delUnit(index, item) {
      if (item.unitId) {
        this.$modal
          .confirm('是否确认删除该单元')
          .then(function() {
            return delUnit(item.unitId)
          })
          .then(() => {
            this.form.unitList.splice(index, 1)
            this.$modal.msgSuccess('删除成功')
          })
          .catch(() => {
          })
      } else {
        this.form.unitList.splice(index, 1)
      }
    },
    //增加单元
    addUnit() {
      this.form.unitList.push({
        unitName: '',
        floors: null,
        buildingId: this.designatedData.buildingId,
      })
    },
    //表单提交
    handleSubmitForm: debounce(function() {
      function hasDuplicateField(arr, field) {
        const uniqueArr = arr.filter((item, index) => {
          return (
            index === arr.findIndex((other) => other[field] === item[field])
          )
        })

        return uniqueArr.length !== arr.length
      }

      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (hasDuplicateField(this.form.unitList, 'unitName')) {
            this.$modal.msgWarning('单元名称请勿重复')
            return false
          }
          batchAddUnit(this.form.unitList).then((response) => {
            this.$modal.msgSuccess('新增成功')
            this.show = false
            this.$emit('success')
          })
          // if (this.form.buildingId) {
          //   editBuilding(this.form).then((response) => {
          //     this.$modal.msgSuccess('编辑成功')
          //     this.show = false
          //     this.$emit('success')
          //   })
          // } else {
          //   addBuilding(this.form).then((response) => {
          //     this.$modal.msgSuccess('新增成功')
          //     this.show = false
          //     this.$emit('success')
          //   })
          // }
        }
      })
    }, 1000, true) //防抖
  }
}
</script>


<style scoped lang="scss">

</style>
